<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../lib/index.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        canvas{
            margin: 50px auto 0;
            display: block;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="400" height="400">
        此浏览器不支持webgl
    </canvas>
</body>
</html>

<script>
    const ctx = document.getElementById('canvas')
    const gl = ctx.getContext('webgl')

    //着色器
    //创建着色器源码
    //顶点着色器
    const VERTEX_SHADER_SOURCE = `
        attribute vec4 aPosition;
        void main(){
            gl_Position = aPosition;
            gl_PointSize = 30.0;
        }
    `
    //片元着色器
    const FRAGMENT_SHADER_SOURCE = `
        void main(){
            //gl_FragColor vec4(1.0, 0.0, 0.0, 1.0) vec4(r, g, b, a)
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    `

    const program = initShader(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE)
    const aPosition = gl.getAttribLocation(program, 'aPosition')

    ctx.onclick = function(e){
        const x = e.clientX
        const y = e.clientY

        // ctx.offsetTop
        // ctx.offsetLeft
        const domPosition = e.target.getBoundingClientRect()
        const domX = x - domPosition.left
        const domY = y - domPosition.top

        const halfWidth = ctx.offsetWidth / 2
        const halfHeight = ctx.offsetHeight / 2

        const clickX = (domX - halfWidth) / halfWidth
        const clickY = (halfHeight - domY) / halfHeight

        gl.vertexAttrib2f(aPosition, clickX, clickY);
        //执行绘制
        gl.drawArrays(gl.POINTS, 0, 1)
    }
</script>